package com.quan.base.common.utils.file;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FileUtils {

	private static final Logger logger = LoggerFactory.getLogger(FileUtils.class);
	
	// 创建目录
	public static File createDir(String dirPath) {
		File dir;
		try {
			dir = new File(dirPath);
			if (!dir.exists()) {
				org.apache.commons.io.FileUtils.forceMkdir(dir);
			}
		} catch (Exception e) {
			logger.error("创建目录出错！", e);
			throw new RuntimeException(e);
		}
		return dir;
	}

	// 创建文件
	public static File createFile(String filePath) {
		File file;
		try {
			file = new File(filePath);
			File parentDir = file.getParentFile();
			if (!parentDir.exists()) {
				org.apache.commons.io.FileUtils.forceMkdir(parentDir);
			}
		} catch (Exception e) {
			logger.error("创建文件出错！", e);
			throw new RuntimeException(e);
		}
		return file;
	}

	// 复制目录（不会复制空目录）
	public static void copyDir(String srcPath, String destPath) {
		try {
			File srcDir = new File(srcPath);
			File destDir = new File(destPath);
			if (srcDir.exists() && srcDir.isDirectory()) {
				org.apache.commons.io.FileUtils.copyDirectoryToDirectory(
						srcDir, destDir);
			}
		} catch (Exception e) {
			logger.error("复制目录出错！", e);
			throw new RuntimeException(e);
		}
	}

	// 复制文件
	public static void copyFile(String srcPath, String destPath) {
		try {
			File srcFile = new File(srcPath);
			File destDir = new File(destPath);
			if (srcFile.exists() && srcFile.isFile()) {
				org.apache.commons.io.FileUtils.copyFileToDirectory(srcFile,
						destDir);
			}
		} catch (Exception e) {
			logger.error("复制文件出错！", e);
			throw new RuntimeException(e);
		}
	}

	// 删除目录
	public static void deleteDir(String dirPath) {
		try {
			File dir = new File(dirPath);
			if (dir.exists() && dir.isDirectory()) {
				org.apache.commons.io.FileUtils.deleteDirectory(dir);
			}
		} catch (Exception e) {
			logger.error("删除目录出错！", e);
			throw new RuntimeException(e);
		}
	}

	// 删除文件
	public static void deleteFile(String filePath) {
		try {
			File file = new File(filePath);
			if (file.exists() && file.isFile()) {
				org.apache.commons.io.FileUtils.forceDelete(file);
			}
		} catch (Exception e) {
			logger.error("删除文件出错！", e);
			throw new RuntimeException(e);
		}
	}

	// 重命名文件
	public static void renameFile(String srcPath, String destPath) {
		File srcFile = new File(srcPath);
		if (srcFile.exists()) {
			File newFile = new File(destPath);
			boolean result = srcFile.renameTo(newFile);
			if (!result) {
				throw new RuntimeException("重命名文件出错！" + newFile);
			}
		}
	}

	// 将字符串写入文件
	public static void writeFile(String filePath, String fileContent) {
		OutputStream os = null;
		Writer w = null;
		FileOutputStream fos = null;
		try {
			FileUtils.createFile(filePath);
			fos = new FileOutputStream(filePath);
			os = new BufferedOutputStream(fos);
			w = new OutputStreamWriter(os, "UTF-8");
			w.write(fileContent);
			w.flush();
		} catch (Exception e) {
			logger.error("写入文件出错！", e);
			throw new RuntimeException(e);
		} finally {
			try {
				if (os != null) {
					os.close();
				}
				if (w != null) {
					w.close();
				}
			} catch (Exception e) {
				logger.error("释放资源出错！", e);
			}
		}
	}

	// 获取真实文件名（去掉文件路径）
	public static String getRealFileName(String fileName) {
		return FilenameUtils.getName(fileName);
	}

	// 判断文件是否存在
	public static boolean checkFileExists(String filePath) {
		return new File(filePath).exists();
	}

	public static byte[] toByteArray(String filename) throws Exception {

		File f = new File(filename);
		if (!f.exists()) {
			logger.error("文件未找到！" + filename);
			throw new Exception("文件未找到！");
		}
		FileChannel channel = null;
		FileInputStream fs = null;
		try {
			fs = new FileInputStream(f);
			channel = fs.getChannel();
			ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size());
			while ((channel.read(byteBuffer)) > 0) {
				// do nothing
				// System.out.println("reading");
			}
			return byteBuffer.array();
		} catch (IOException e) {
			throw new Exception("FILE_READING_ERROR");
		} finally {
			try {
				channel.close();
			} catch (IOException e) {
				throw new Exception("FILE_READING_ERROR");
			}
			try {
				fs.close();
			} catch (IOException e) {
				throw new Exception("FILE_READING_ERROR");
			}
		}
	}

	/**
	 * 获取文件类型
	 * 注意：需要使用jdk1.7及以上
	 * @param filename
	 * @return
	 */
	public static String getContentType(String filename){  
        String type = null;  
        Path path = Paths.get(filename);  
        try {  
            type = Files.probeContentType(path);  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        return type;  
    }  
}
